<?php
/**
 * Create By: PhpStorm
 * User: niechenguang
 * File: GetCircle.php
 * Date: 2017/1/2
 * Time: 23:13
 */

namespace app\api\model\page\circle;

use app\api\model\dao\Circle;
use app\api\model\dao\CircleStatistics;
use app\library\Error;
use app\library\Flag;
use app\library\PageBase;
use think\Exception;

class GetCircleRecommend extends PageBase
{

    private $objCircle;
    private $objCircleStatistics;

    public function __construct()
    {
        parent::__construct();

        $this->objCircle = new Circle();
        $this->objCircleStatistics = new CircleStatistics();

    }

    /**
     * page 入口
     *
     * @param $param
     * @return array
     * @throws Exception
     */
    public function myExcute($param)
    {
        // 1、获取推荐商圈列表
        $ret = $this->getCircleRecommend();
        if (false === $ret) {
            throw new Exception('get circle recommend list fail. ', Error::ERR_SYS);
        }

        $this->data = $this->composeData($ret);
    }

    /**
     * 从数据库中获取圈子详情
     *
     * @param $cir_id
     * @return bool|false|\PDOStatement|string|\think\Collection
     */
    public function getCircleRecommend()
    {

        $cir_pv = $this->objCircleStatistics->getCirclePvTop('1=1', 10);
        if (empty($cir_pv)) {
            return [];
        }

        $cir_id = [];
        $cirid2Pv = [];
        foreach ($cir_pv as $val) {
            $cir_id[] = $val['cir_id'];
            $cirid2Pv[$val['cir_id']] = $val['pv_sum'];
        }

        $conds = [
            'id' => ['in', $cir_id],
            'approve_status' => ['=', Flag::CONST_CIRCLE_APPROVE_PASS],
            'is_delete' => ['=', Flag::CONST_CIRCLE_DELETE_NOT],
        ];

        $circle = $this->objCircle->getCircle($conds);
        if (empty($circle)) {
            return [];
        }

        foreach ($circle as &$val) {
            $val['pv'] = !empty($cirid2Pv[$val['id']]) ? $cirid2Pv[$val['id']] : 0;
        }
        unset($val);

        return $circle;
    }

    public function composeData($arrCircle)
    {
        $data = [];
        foreach ($arrCircle as $val) {
            $word = [];
            if (!empty($val['label'])) {
                $word = explode(',', $val['label']);
            }
            $data[] = [
                'cir_id' => $val['id'],
                'name' => $val['name'],
                'icon' => $val['icon'] ? $val['icon'] : Flag::CONST_CIRCLE_DEFAULT_ICON,
                'pv' => $val['pv'],
                'word' => $word,
            ];
        }
        return $data;
    }
}
